package com.yangdada.service.facade;

import com.yangdada.dto.PublicDataDTO;
import com.yangdada.dto.PublicRequestDTO;
import com.yangdada.dto.TwoDataTestResponseDTO;
import com.yangdada.service.IBlogService;
import com.yangdada.utils.DateReplenishUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DateFacade {

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private IBlogService blogService;

    public Map<String, Object> getTwoData(PublicRequestDTO publicRequestDTO) throws InterruptedException {
        Map<String, Object> map = new HashMap<>();
        CountDownLatch latch = new CountDownLatch(2);
        taskExecutor.execute(() ->{
            TwoDataTestResponseDTO twoDataTestResponseData = blogService.getTwoDataTestResponseData(publicRequestDTO);
            map.put("twoDataTestResponseData",twoDataTestResponseData);
            latch.countDown();
        });

        taskExecutor.execute(()->{
            List<PublicDataDTO> twoDataTest = blogService.getTwoDataTest(publicRequestDTO);
            Map<String, PublicDataDTO> collect = twoDataTest.stream().collect(Collectors.toMap(PublicDataDTO::getDate, Function.identity(), (k, v) -> k));
            try {
                List<PublicDataDTO> publicDataDTOS = DateReplenishUtil.dateReplenish(collect, new PublicDataDTO(), publicRequestDTO.getStartDate(), publicRequestDTO.getEndDate());
                List<PublicDataDTO> collect1 = publicDataDTOS.stream().sorted((k, v) -> k.getDate().compareTo(v.getDate())).collect(Collectors.toList());
                map.put("twoDateList",collect1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            latch.countDown();
        });
        latch.await();
        return map;
    }
}
